#!/usr/bin/env python

#root [3] tt->GetListOfLeaves()->Print()
#Collection name='TObjArray', class='TObjArray', size=21
# OBJ: TLeafI    EventNumber     EventNumber
# OBJ: TLeafS    Temperature     Temperature
# OBJ: TLeafS    ASIC_TRGbias    ASIC_TRGbias[4][4]
# OBJ: TLeafS    ASIC_TRGthresh  ASIC_TRGthresh[4][4][8]
# OBJ: TLeafS    ASIC_Wbias      ASIC_Wbias[4][4]
# OBJ: TLeafS    ASIC_VadjP      ASIC_VadjP[4][4]
# OBJ: TLeafS    ASIC_VadjN      ASIC_VadjN[4][4]
# OBJ: TLeafS    ASIC_Vbias      ASIC_Vbias[4][4]
# OBJ: TLeafS    ASIC_SBbias     ASIC_SBbias[4][4]
# OBJ: TLeafS    ASIC_Isel       ASIC_Isel[4][4]
# OBJ: TLeafS    ASIC_CMPbias    ASIC_CMPbias[4][4]
# OBJ: TLeafS    ASIC_PUbias     ASIC_PUbias[4][4]
# OBJ: TLeafS    ASIC_Vdly       ASIC_Vdly[4][4]
# OBJ: TLeafS    ASIC_TRGthreshref       ASIC_TRGthreshref[4][4]
# OBJ: TLeafS    ASIC_WilkCounter        ASIC_WilkCounter[4][4]
# OBJ: TLeafS    ASIC_SampRateCounter    ASIC_SampRateCounter[4][4]
# OBJ: TLeafS    ASIC_TrigWidthCounter   ASIC_TrigWidthCounter[4][4]
# OBJ: TLeafF    ASIC_ADC        ASIC_ADC[4][4][8][4][64]
# OBJ: TLeafS    ASIC_OriginWindow       ASIC_OriginWindow[4][4][8][4]
# OBJ: TLeafO    ASIC_TriggerStream      ASIC_TriggerStream[4][4][8][16]
# OBJ: TLeafS    ASIC_Scaler     ASIC_Scaler[4][4][8]
#
# ASIC_ADC[asic_col][asic_row][asic_chan][window][sample]

from collections import defaultdict
import optparse
from os.path import basename
import sys

import numpy
import ROOT
import tables

from charmicat import BadCommandLineError

def main():
    '''
    dst2pt.py [opts] file.dst2 [file.camac]
    
    Convert fields in `file.dst2' to PyTables arrays.
    '''

    op = optparse.OptionParser(usage=main.__doc__)
    
    opts, args = op.parse_args()

    if len(args) < 1:
        msg = "Please supply a DST2 file and "
        msg += "its associated CAMAC file as input."
        raise BadCommandLineError(msg, -1)

    f_dst2 = ROOT.TFile(args[0])
    t_dst2 = f_dst2.Get("EventTree")

    if len(args) > 1:
        f_camac = ROOT.TFile(args[1])
        t_camac = f_camac.Get("camdata")
    else:
        f_camac = None
        t_camac = None

    fields = defaultdict(list)

    outfile = basename(args[0]).rsplit('.')[0] + '.h5'
    with tables.openFile(outfile, 'w') as fpout:
        adc = fpout.createEArray(fpout.root, 'adc', tables.Float32Atom(), 
                                 shape=(0,4,4,8,4,64))
        win = fpout.createEArray(fpout.root, 'win', tables.UInt16Atom(),
                                 shape=(0,4,4,8,4))

        nrow = t_dst2.GetEntries()
        for i in xrange(t_dst2.GetEntries()):
            if t_dst2.LoadTree(i) < 0:
                break
            if t_dst2.GetEntry(i) < 0:
                continue

            adc.append(
                [numpy.reshape([x for x in t_dst2.ASIC_ADC],
                              (4,4,8,4,64))])
            win.append(
                [numpy.reshape([x for x in t_dst2.ASIC_OriginWindow],
                              (4,4,8,4))])

            fields['eventno'].append(t_dst2.EventNumber)
            fields['temp'].append(t_dst2.Temperature)

            sys.stdout.write("{}/{} complete\r".format(i, nrow))
            sys.stdout.flush()

        print

        f_dst2.Close()

        if t_camac is not None:
            for i in xrange(t_camac.GetEntries()):
                if t_camac.LoadTree(i) < 0:
                    break
                if t_camac.GetEntry(i) < 0:
                    continue

                fields['ftsw'].append(t_camac.ftsw)

            f_camac.Close()

        for f in fields:
            fpout.createArray(fpout.root, f, numpy.array(fields[f]))
                        
    return 0


if __name__ == '__main__':
    try:
        import sys
        sys.exit(main())
    except BadCommandLineError, e:
        import os
        sys.stderr.write(str(e) + "\n")
        sys.stderr.write("See `{0} -h' for more.\n".format(
                os.path.basename(sys.argv[0])))
        sys.stderr.flush()
        sys.exit(e.retcode)
